﻿namespace MapleRock.P2PEmulator.Core
{
  using System;
  using System.Collections.Generic;
  using System.Diagnostics;
  using System.Linq;
  using System.Text;

  public sealed class AdjacencyTable
  {
    private bool[,] table = null;

    public AdjacencyTable(int peersNumber)
    {
      Debug.Assert(peersNumber > 0, "peersNumber > 0");

      // assume that the array will be filled by the false values by default
      this.table = new bool[peersNumber, peersNumber];
    }

    public int Size
    {
      get { return this.table.GetLength(0); }
    }

    public void Connect(uint a, uint b)
    {
      this.table[a, b] = true;
      this.table[b, a] = true;
    }

    public void Disconnect(uint a, uint b)
    {
      this.table[a, b] = false;
      this.table[b, a] = false;
    }

    public List<uint> GetAdjacentEntries(uint a)
    {
      var result = new List<uint>();

      for (var i = 0; i < this.table.GetLength(0); ++i)
      {
        if (this.table[a, i])
        {
          result.Add(Convert.ToUInt32(i));
        }
      }

      return result;
    }

    public int GetAdjacentEntriesCount(uint a)
    {
      var counter = 0;

      for (var i = 0; i < this.table.GetLength(0); ++i)
      {
        if (this.table[a, i])
        {
          ++counter;
        }
      }

      return counter;
    }

    public bool IsAdjacent(uint a, uint b)
    {
      return this.table[a, b];
    }

    public override string ToString()
    {
      var result = new StringBuilder();
      result.Append(this.table.GetLength(0));
      result.Append(" ");

      foreach (var entry in this.table)
      {
        result.Append(entry ? "1 " : "0 ");
      }

      return result.ToString().TrimEnd();
    }
  }
}
